/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.office.notify.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;

import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.CrudService;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.websocket.SystemWebSocketHandler;
import cn.knet.sp.ncrm.modules.office.notify.dao.OfficeNotifyDao;
import cn.knet.sp.ncrm.modules.office.notify.entity.OfficeNotify;
import cn.knet.sp.ncrm.modules.office.notify.entity.OfficeNotifyRecord;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.user.service.SystemService;

/**
 * 系统通知、预约提醒Service
 * @author gehaiyang
 * @version 2015-07-20
 */
@Service
@Transactional(readOnly = true)
public class OfficeNotifyService extends CrudService<OfficeNotifyDao, OfficeNotify> {

	@Resource
	private OfficeNotifyRecordService officeNotifyRecordService;
	@Resource
	private SystemService systemService;
	@Resource
	private SystemWebSocketHandler systemWebSocketHandler;
	
	public OfficeNotify get(String id) {
		return super.get(id);
	}
	
	public List<OfficeNotify> findList(OfficeNotify officeNotify) {
		return super.findList(officeNotify);
	}
	
	public Page<OfficeNotify> findPage(Page<OfficeNotify> page, OfficeNotify officeNotify) {
		return super.findPage(page, officeNotify);
	}
	
	@Transactional(readOnly = false)
	public void save(OfficeNotify officeNotify) {
		super.save(officeNotify);
	}
	
	@Transactional(readOnly = false)
	public void delete(OfficeNotify officeNotify) {
		super.delete(officeNotify);
	}
	
	public void send(OfficeNotify officeNotify){
		if (StringUtils.isNotBlank(officeNotify.getId())) {
			//添加通知记录
			OfficeNotifyRecord officeNotifyRecord = null;
			for (String officeId : officeNotify.getOfficeIds()) {
				for (User user : systemService.findUserByOfficeId(officeId)) {
					officeNotifyRecord = new OfficeNotifyRecord();
					officeNotifyRecord.setOfficeNotify(officeNotify);
					officeNotifyRecord.setUser(user);
					officeNotifyRecord.setReadFlag("0");//设置未读
					officeNotifyRecordService.save(officeNotifyRecord);
					//推送消息通知
					systemWebSocketHandler.sendMessageToUser(user, new TextMessage("1"));
				}
			}
		}
	}
}